'use strict';

const BaseController = require('./base');

class RoleController extends BaseController {
  get _service() {
    return 'role';
  }

  async create() {
    const { ctx } = this;
    const { name, auth, description } = ctx.params();
    const result = await this.service.role.create({ name, auth, description });
    if (result) {
      this.success();
    } else {
      this.error('创建角色失败');
    }
  }

  async update() {
    const { ctx } = this;
    const { name, auth, description } = ctx.params();
    const { id } = ctx.params;
    if (+id === 2) {
      this.error('修改失败');
      return;
    }
    const result = await this.service.role.update({ name, auth, description, id });
    if (result) {
      this.success();
    } else {
      this.error('更新角色失败');
    }
  }

  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    if (+id === 2) {
      this.error('删除失败');
      return;
    }
    const user = await ctx.service.userAndRole.findOne({ rid: id });
    if (user) {
      this.error('删除失败');
      return;
    }
    const result = await this._getService().destory(+id);
    if (result) {
      this.success();
    } else {
      this.error('删除失败');
    }
  }

  async show() {
    await this._show('获取角色失败');
  }

  async index() {
    const { ctx } = this;
    const { name, description, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const result = await this.service.role.findList({ name, description, prop, sort, pageIndex, pageSize, createdAt });
    if (result) {
      this.success(result.data, result.count);
    } else {
      this.error('获取角色失败');
    }
  }

  async all() {
    await this._all('获取角色失败');
  }
}

module.exports = RoleController;
